from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from orders.models import OrderInfo
from meiduo_admin.my_paginate import MyPageNuberPagination
from meiduo_admin.order.order_serializers import OrderSerializer,OrderModelSerializer
from rest_framework.response import Response


class OrderViewSet(ModelViewSet):
    pagination_class = MyPageNuberPagination
    # serializer_class = OrderSerializer
    # queryset = OrderInfo.objects.all()

    #重写queryset
    def get_queryset(self):
        keyword=self.request.query_params.get("keyword")

        if keyword:
            return OrderInfo.objects.filter(order_id__contains=keyword).all()
        else:
            return OrderInfo.objects.all()

        #另一种写法,效果等同
        # # 1,获取参数
        # keyword = self.request.query_params.get("keyword", "")
        #
        # # 2,返回结果
        # return OrderInfo.objects.filter(order_id__contains=keyword).all()

    #重写serializer_class
    def get_serializer_class(self):
        if self.action == "retrieve":
            return OrderModelSerializer
        else:
            return OrderSerializer

     # 2,修改订单状态
    #等同于路由url(r'^orders/(?P<pk>\w+)/status/$',order_views.OrderViewSet.as_view({"put':"status"}))
    @action(methods=["put"],detail=True)# 格式: orders/pk/status
    def status(self,request,pk):

        # 1,获取参数
        status=request.data.get("status")
        order=self.get_object()#通过pk到数据源获取订单对象
        print(order)
        # 2,校验参数
        if not all([status,order]):
            return Response(status=403)

        # 3,数据入库
        order.status=status
        order.save()
        #4返回数据
        return Response(status=201)
